# -*- coding: utf-8 -*-
"""
    :author: FanZhong (范钟)
    :copyright: © 2018 FanZhong <coder.fan@qq.com>
    :license: MIT, see LICENSE for more details.
"""

from flask import Blueprint, redirect, url_for, render_template, flash
from flask_login import login_user, logout_user, login_required, current_user
from fblog import forms, models, utils

auth_bp = Blueprint('auth', __name__)


@auth_bp.route("/", methods=["GET"])
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for("blog.index"))
    form = forms.LoginForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        remember = form.remember.data

        admin = models.Admin.query.first()
        if admin:
            if admin.username == username and admin.validate_password(password):
                login_user(admin, remember)
                flash("登陆成功", 'info')
                return utils.redirect_back()
            flash("账号或者密码错误", "warning")
        else:
            flash("没有后台管理账号", "warning")
    return render_template('auth/login.html', form=form)


@auth_bp.route("/logout")
@login_required
def logout():
    logout_user()
    flash("退出成功", "info")
    return utils.redirect_back()
